package com.acooly.module.openapi.client.provider.alipay.notify;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.acooly.core.common.exception.BusinessException;
import com.acooly.core.common.web.servlet.AbstractSpringServlet;
import com.acooly.core.utils.Servlets;
import com.acooly.core.utils.Strings;
import com.acooly.module.openapi.client.api.notify.NotifyHandlerDispatcher;
import com.acooly.module.openapi.client.common.enums.ResultCodeEnum;

import lombok.extern.slf4j.Slf4j;

/**
 * @author zhike 2017/12/1 20:09
 */
@Slf4j
public class AlipayApiServiceClientServlet extends AbstractSpringServlet {

    /**
     * UID
     */
    private static final long serialVersionUID = 6169228472722574634L;

    private NotifyHandlerDispatcher notifyHandlerDispatcher;

    private static final int SUCCESS_RESPONSE_CODE = 200;
    private static final String SUCCESS_RESPONSE_BODY = "success";
    private static final String DEFAULT_NOTIFY_DISPATCHER_BEAN_NAME = "clientNotifyHandlerDispatcher";

    public static final String SUCCESS_RESPONSE_CODE_KEY = "success_response_code";
    public static final String SUCCESS_RESPONSE_BODY_KEY = "success_response_body";
    public static final String NOTIFY_DISPATCHER_BEAN_NAME_KEY = "NOTIFY_DISPATCHER_BEAN_NAME_KEY";

    @Override
    protected void doInit() {
        super.doInit();
        notifyHandlerDispatcher = getBean(getDispatcherBeanName(), NotifyHandlerDispatcher.class);
        log.info("Initializing Spring-based Servlet '" + getServletName() + "', notify name:{},bean:{}",getDispatcherBeanName(),notifyHandlerDispatcher);
    }

    @Override
    protected void doService(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            Map<String, String> notifyData = conversionNotifyDataToMap(request);
            String notifyUrl = Servlets.getRequestPath(request);
            notifyHandlerDispatcher.dispatch(notifyUrl, notifyData);
            response.setStatus(getSuccessResponseCode());
            Servlets.writeResponse(response, getSuccessResponseBody(), null);
        } catch (Exception e) {
            Servlets.writeResponse(response, "fail", null);
        }
    }

    private Map<String, String> conversionNotifyDataToMap(HttpServletRequest request) {
    	Map<String,String> params = new HashMap<String,String>();
        try {
        	/**
        	 request.setCharacterEncoding("utf-8");
             String resString = XmlUtils.parseRequst(request);
             if (resString != null && !"".equals(resString)) {
                 map = XmlUtils.toMap(resString.getBytes(), "utf-8");
             } else {
                 throw new BusinessException("异步报文不能为空", ResultCodeEnum.EXECUTE_FAIL.getCode());
             }
        	 */
    		Map requestParams = request.getParameterMap();
    		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
    			String name = (String) iter.next();
    			String[] values = (String[]) requestParams.get(name);
    			String valueStr = "";
    			for (int i = 0; i < values.length; i++) {
    				valueStr = (i == values.length - 1) ? valueStr + values[i]
    						: valueStr + values[i] + ",";
    			}
    			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
    			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
    			params.put(name, valueStr);
    		}
            return params;
        } catch (Exception e) {
            throw new BusinessException("异步报文转化验签错误", ResultCodeEnum.EXECUTE_FAIL.getCode());
        }
    }

    protected String getDispatcherBeanName() {
        String beanName = getInitParameter(NOTIFY_DISPATCHER_BEAN_NAME_KEY);
        if (Strings.isBlank(beanName)) {
            beanName = DEFAULT_NOTIFY_DISPATCHER_BEAN_NAME;
        }
        return beanName;
    }

    protected String getSuccessResponseBody() {
        String body = getInitParameter(SUCCESS_RESPONSE_BODY_KEY);
        if (Strings.isBlank(body)) {
            body = SUCCESS_RESPONSE_BODY;
        }
        return body;
    }

    protected int getSuccessResponseCode() {
        try {
            return Integer.parseInt(getInitParameter(SUCCESS_RESPONSE_CODE_KEY));
        } catch (Exception e) {
            return SUCCESS_RESPONSE_CODE;
        }
    }
}
